﻿using System; using HISModels.ViewModel;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using KeanuMvc.Reference;
using HIS.Utils;
using System.Reflection;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using HISModels.Entities;
using System.Net;
using System.Configuration;
using HISModels.ViewModel;

namespace HIS.Controllers.Admins {

    public class NavigationGroup : HIS.Controllers.AppBaseController {

        #region Fields
        private string strAction = string.Empty;
        private string strNotification = string.Empty;
        private HISModels.Entities.SysNavigationGroup sysNavigationGroup = null;
        private HISModels.Entities.SysNavigation sysNavigation = null;
        #endregion

        #region Navigation Group
        public NavigationGroup() {
            Data.Add("Pagetitle", "Navigation Groups");
            Data.Add("Notification", strNotification);
        }

        [HIS.Utils.Securities.Authorization(RoleAction = "sys-navigation")]
        public override void Index() {
            try {
                Data.Add("ddlHospitals", DropDownHospital(string.Empty));
                RenderFile("admins\\navigations\\navigationgroup.html");
            } catch (Exception ex) {
                HttpContext.Current.Response.Write(ex.Message);
            }
        }

        [HIS.Utils.Securities.Authorization(RoleAction = "sys-navigation")]
        public void TableList() {
            try {
                ///--------- Sample post to rest and get record as paging-------------/// 
                ///Create paging object///
                PostDataTablesNet pagingSearch = new PostDataTablesNet();
                pagingSearch.iDisplayLength = Convert.ToInt32(HttpContext.Current.Request["iDisplayLength"]);
                pagingSearch.iDisplayStart = Convert.ToInt32(HttpContext.Current.Request["iDisplayStart"]);

                string groupname = HttpContext.Current.Request["groupname"].NullSafeToString();
                string rolename = HttpContext.Current.Request["rolename"].NullSafeToString();
                int hospitalid = Convert.ToInt32(HttpContext.Current.Request["hospitalid"]);


                pagingSearch.sSearch = "groupname=" + groupname + ";rolename=" + rolename + ";hospitalid=" + hospitalid;

                pagingSearch.sEcho = Convert.ToInt32(HttpContext.Current.Request["sEcho"]);
                //
                ///Set Rest Url///
                string strUri = Global.ServiceUriDictionary["navgroupspaging"] + Global.ServiceUriDictionary["requestformat"];
                ///Post paging object to rest as json string///
                StringReader stringReader = base.RestService.PostJson(strUri, JsonConvert.SerializeObject(pagingSearch));
                ///Read response value///
                string strJson = stringReader.ReadToEnd();
                ///----------Consistenly clean up all object------------///
                stringReader.Dispose();
                base.RestService.Dispose();
                HttpContext.Current.Response.Write(strJson);
            } catch (Exception ex) {
                HttpContext.Current.Response.Write(ex.Message);
            }
        }

        [HIS.Utils.Securities.Authorization(RoleAction = "sys-navigation")]
        public void AnotherWayToReadJson() {
            try {
                PostDataTablesNet pagingSearch = new PostDataTablesNet();
                pagingSearch.iDisplayLength = Convert.ToInt32(HttpContext.Current.Request["iDisplayLength"]);
                pagingSearch.iDisplayStart = Convert.ToInt32(HttpContext.Current.Request["iDisplayStart"]);
                pagingSearch.sSearch = HttpContext.Current.Request["sSearch"];
                pagingSearch.sEcho = Convert.ToInt32(HttpContext.Current.Request["sEcho"]);

                string strUri = Data["servicerooturl"] + "sys/navigations/group/paging/?format=json";
                StringReader stringReader = base.RestService.PostJson(strUri, JsonConvert.SerializeObject(pagingSearch));

                JObject o = JObject.Parse(stringReader.ReadToEnd());
                int TotalRecords = (int)o["iTotalRecords"];
                int TotalDisplayRecords = (int)o["iTotalDisplayRecords"];
                JArray aaData = (JArray)o["aaData"];

                string strJsjon = "{\"sEcho\": " + pagingSearch.sEcho + ", " +
                                      "\"iTotalRecords\": \"" + TotalRecords.ToString() + "\"," +
                                      "\"iTotalDisplayRecords\": \"" + TotalDisplayRecords.ToString() + "\"," +
                                      "\"aaData\": [";
                string[] arrData = new string[aaData.Count()];

                int iLoop = 0;
                string strButton = string.Empty;

                for (int i = 0; i < aaData.Count(); i++) {
                    JObject oo = JObject.Parse(aaData[i].ToString());
                    int Id = (int)oo["Id"];
                    string Name = (string)oo["DescValue"];
                    arrData[iLoop] = string.Format(
                        "[{0},{1}]",
                        Id.ToString().AddDoubleQuote(),
                        Name.AddDoubleQuote()
                        );
                    iLoop++;
                }

                strJsjon = strJsjon + string.Join(",", arrData);
                strJsjon += "]}";
                base.RestService.Dispose();
                HttpContext.Current.Response.Write(strJsjon);
            } catch (Exception ex) {
                HttpContext.Current.Response.Write(ex.Message);
            }
        }

        [HIS.Utils.Securities.Authorization(RoleAction = "sys-navigation")]
        public void EditNavigationGroup() {      
            StringReader stringReader = null;
            int id = 0;
            try {
                id = Convert.ToInt32(HttpContext.Current.Request["id"]);
            } catch {
                GoToUrl("navigationgroups/"); return;
            }

            try {
                string strUri = Global.ServiceUriDictionary["navgroups"] + id + Global.ServiceUriDictionary["requestformat"];
                stringReader = base.RestService.GetJson(strUri);
                sysNavigationGroup = JsonConvert.DeserializeObject<SysNavigationGroup>(stringReader.ReadToEnd());
                //sysNavigationGroup.SysRole.DescValue
                Data.Add("sysNavigationGroup", sysNavigationGroup);
                Data.Add("IsCreate", "false");
            } catch (Exception ex) {
                Data["Notification"] = Helper.ErrorMessage(ex.Message);
            } finally {
                RenderFile("Admins\\Navigations\\editnavigationgroup.html");
                stringReader.Dispose();
                base.RestService.Dispose();
            }
        }

        [HIS.Utils.Securities.Authorization(RoleAction = "sys-navigation")]
        public void DeleteNavigationGroup() {
            StringReader stringReader = null;
            int id = 0;
            try {
                id = Convert.ToInt32(HttpContext.Current.Request["id"]);
            } catch {
                GoToUrl("navigationgroups/");
                return;
            }

            try {
                string strUri = Global.ServiceUriDictionary["navgroups"] + Global.ServiceUriDictionary["requestformat"];

                sysNavigationGroup = new HISModels.Entities.SysNavigationGroup();
                stringReader = base.RestService.DeleteJson(strUri, JsonConvert.SerializeObject(id));
                sysNavigationGroup = JsonConvert.DeserializeObject<SysNavigationGroup>(stringReader.ReadToEnd());

                if (sysNavigationGroup != null) {
                    strNotification = Helper.SuccessMessage(base.RestService.ObjectResponse.Headers[HISModels.Enums.ResponseMessage.DetailHeadesMessageKey].ToString());
                } else {
                    strNotification = Helper.ErrorMessage(base.RestService.ObjectResponse.Headers[HISModels.Enums.ResponseMessage.DetailHeadesMessageKey].ToString());
                }

                strNotification = "{\"strNotification\": \"" + strNotification + "\"}";

            } catch (Exception ex) {
                strNotification = ex.Message;
            } finally {
                HttpContext.Current.Response.Write(strNotification);
                if (stringReader != null) stringReader.Dispose();
            }
        }

        [HIS.Utils.Securities.Authorization(RoleAction = "sys-navigation")]
        public void CreateNavigationGroup() {
            try {
                Data["Pagetitle"] += " :: Add Navigation Group";
                sysNavigationGroup = new HISModels.Entities.SysNavigationGroup() { DescValue = string.Empty };
                sysNavigationGroup.SysRole = new SysRole() { DescValue = string.Empty };
                Data.Add("sysNavigationGroup", sysNavigationGroup);
                Data.Add("IsCreate", "true");
                Data["Notification"] = strNotification;

            } catch (Exception ex) {
                Data["Notification"] = Helper.ErrorMessage(ex.Message);
            } finally {
                RenderFile("Admins\\Navigations\\editnavigationgroup.html");
                base.RestService.Dispose();
            }
        }

        [HIS.Utils.Securities.Authorization(RoleAction = "sys-navigation")]
        public void SaveNavigationGroup() {
            StringReader stringReader = null;
            string strUri = string.Empty;
            try {
                sysNavigationGroup = new SysNavigationGroup(); Utils.Helper.SetNullToEmptyString(sysNavigationGroup);
                if (HttpContext.Current.Request["IsCreate"] != "true") {
                    int id = 0;
                    try {
                        id = Convert.ToInt32(HttpContext.Current.Request["id"]);
                    } catch { }
                    strUri = Global.ServiceUriDictionary["navgroups"] + id + Global.ServiceUriDictionary["requestformat"];
                    ///Get Rest///
                    stringReader = base.RestService.GetJson(strUri);
                    sysNavigationGroup = JsonConvert.DeserializeObject<SysNavigationGroup>(stringReader.ReadToEnd());
                } 

                sysNavigationGroup.PostHandler<HISModels.Entities.SysNavigationGroup>();
                sysNavigationGroup.SysRole = null;

                strUri = Global.ServiceUriDictionary["navgroups"] + Global.ServiceUriDictionary["requestformat"];

                if (HttpContext.Current.Request["IsCreate"] == "true") {
                    stringReader = base.RestService.PostJson(strUri, JsonConvert.SerializeObject(sysNavigationGroup));
                } else {
                    stringReader = base.RestService.PutJson(strUri, JsonConvert.SerializeObject(sysNavigationGroup));
                }


                sysNavigationGroup = JsonConvert.DeserializeObject<SysNavigationGroup>(stringReader.ReadToEnd());

                if (sysNavigationGroup != null) {
                    strNotification = Helper.SuccessMessage(base.RestService.ObjectResponse.Headers[HISModels.Enums.ResponseMessage.DetailHeadesMessageKey].ToString());
                } else {
                    strNotification = Helper.ErrorMessage(base.RestService.ObjectResponse.Headers[HISModels.Enums.ResponseMessage.DetailHeadesMessageKey].ToString());
                }


                strNotification = "{\"strNotification\": \"" + strNotification + "\"}";
                HttpContext.Current.Response.Write(strNotification);

            } catch (Exception ex) {
                strNotification = ex.Message;
            } finally {
                
                base.RestService.Dispose();
            }
        }

        public string DropDownHospital(string Selected) {
            StringReader stringReaderDropDown = null;
            string strResult = string.Empty;
            string Name = string.Empty;
            string strUri = "";
            strUri = Global.ServiceUriDictionary["hospital"] + Global.ServiceUriDictionary["requestformat"];
            try {
                stringReaderDropDown = base.RestService.GetJson(strUri);
                List<HISModels.Entities.RefHu> listSp = JsonConvert.DeserializeObject<List<RefHu>>(stringReaderDropDown.ReadToEnd());
                List<object[]> activeArr = new List<object[]>();

                activeArr.Add(new object[] { -1, Name = "- All Hospitals -" });

                foreach (RefHu item in listSp) activeArr.Add(new object[] { item.Id, Name = item.NameValue });

                strResult = KeanuMvc.Reference.Html.DropDown("hospitalid", string.Empty, activeArr, Selected);
                activeArr.Clear();
                activeArr = null;
            } catch {
            } finally {
                if (stringReaderDropDown != null) stringReaderDropDown.Dispose();
            }
            return strResult;
        }

        public string DropDownRoles(string Selected) {
            StringReader stringReaderDropDown = null;
            string strResult = string.Empty;
            string Name = string.Empty;
            string strUri = "";
            strUri = Global.ServiceUriDictionary["role"] + Global.ServiceUriDictionary["requestformat"];
            try {
                stringReaderDropDown = base.RestService.GetJson(strUri);
                List<HISModels.Entities.SysRole> listSp = JsonConvert.DeserializeObject<List<SysRole>>(stringReaderDropDown.ReadToEnd());
                List<object[]> activeArr = new List<object[]>();

                foreach (SysRole item in listSp) activeArr.Add(new object[] { item.RoleId, Name = item.DescValue });

                strResult = KeanuMvc.Reference.Html.DropDown("RoleId", string.Empty, activeArr, Selected);
                activeArr.Clear();
                activeArr = null;
            } catch {
            } finally {
                if (stringReaderDropDown != null) stringReaderDropDown.Dispose();
            }
            return strResult;
        }

        #endregion

        #region Navigation

        [HIS.Utils.Securities.Authorization(RoleAction = "sys-navigation")]
        public void SettingNavigation() {
            int groupid = 0;
            try {
                groupid = Convert.ToInt32(HttpContext.Current.Request["groupid"]);
            } catch {
                GoToUrl("navigationgroup/");
                return;
            }
            try {
                string strUri = Global.ServiceUriDictionary["navgroups"] + groupid + Global.ServiceUriDictionary["requestformat"];
                StringReader stringReader = base.RestService.GetJson(strUri);
                HISModels.Entities.SysNavigationGroup sysNavigationGroup = JsonConvert.DeserializeObject<SysNavigationGroup>(stringReader.ReadToEnd());

                Data["Pagetitle"] = "Navigation :: Setting Navigation (" + sysNavigationGroup.DescValue + ")";
                Data.Add("NavigationList", HIS.Utils.Helper.GenerateNavigationAdmin(base.RestService, groupid));
                Data.Add("NavigationGroupID", sysNavigationGroup.Id.NullSafeToString());
                RenderFile("admins\\navigations\\viewnavigation.html");
            } catch (Exception ex) {
                HttpContext.Current.Response.Write(ex.Message);
            }
        }

        [HIS.Utils.Securities.Authorization(RoleAction = "sys-navigation")]
        public void EditNavigationSetting() {
            int id = 0;
            int groupid = 0;
            try {
                id = Convert.ToInt32(HttpContext.Current.Request["id"]);
                groupid = Convert.ToInt32(HttpContext.Current.Request["groupid"]);
            } catch {
                GoToUrl("navigationgroup/");
                return;
            }

            try {
                string strUri = Global.ServiceUriDictionary["nav"] + id + Global.ServiceUriDictionary["requestformat"];
                StringReader stringReader = base.RestService.GetJson(strUri);
                sysNavigation = JsonConvert.DeserializeObject<SysNavigation>(stringReader.ReadToEnd());
                Data.Add("sysNavigation", sysNavigation);
                Data.Add("ddParentNavigation", GetParentNavigation(sysNavigation.ParentId.NullSafeToString(), sysNavigation.NavigationGroupId, sysNavigation.Id));
                Data["Pagetitle"] = "Navigation :: Setting Navigation (" + sysNavigation.DescValue + ")";
                Data.Add("IsCreate", "false");
            } catch (Exception ex) {
                Data["Notification"] = Helper.ErrorMessage(ex.Message);
            } finally {
                RenderFile("Admins\\Navigations\\editnavigation.html");
                base.RestService.Dispose();
            }
        }

        [HIS.Utils.Securities.Authorization(RoleAction = "sys-navigation")]
        public void CreateNavigationSetting() {
            int groupid = 0;
            try {
                groupid = Convert.ToInt32(HttpContext.Current.Request["groupid"]);
            } catch {
                GoToUrl("navigationgroup/");
                return;
            }

            try {
                sysNavigation = new HISModels.Entities.SysNavigation() { DescValue = string.Empty, Url = string.Empty};
                sysNavigation.NavigationGroupId = groupid;
                Data.Add("sysNavigation", sysNavigation);
                Data.Add("ddParentNavigation", GetParentNavigation(sysNavigation.ParentId.NullSafeToString(), sysNavigation.NavigationGroupId, sysNavigation.Id));
                Data["Pagetitle"] = "Navigation :: Setting Navigation (" + sysNavigation.DescValue + ")";
                Data.Add("IsCreate", "true");
                Data["Notification"] = strNotification;
            } catch (Exception ex) {
                Data["Notification"] = Helper.ErrorMessage(ex.Message);
            } finally {
                RenderFile("Admins\\Navigations\\editnavigation.html");
                base.RestService.Dispose();
            }
        }

        [HIS.Utils.Securities.Authorization(RoleAction = "sys-navigation")]
        public void DeleteNavigationSetting() {
            int id = 0;
            int groupid = 0;
            try {
                groupid = Convert.ToInt32(HttpContext.Current.Request["groupid"]);
                id = int.Parse(HttpContext.Current.Request["id"]);
            } catch {
                GoToUrl("navigationgroup/");
                return;
            }
            try {
                string strUri = Data["servicerooturl"] + "sys/navigations/?format=json";
                StringReader strReader = base.RestService.DeleteJson(strUri, JsonConvert.SerializeObject(id));
                strNotification = JsonConvert.DeserializeObject<string>(strReader.ReadToEnd());

                if (string.IsNullOrEmpty(strNotification)) strNotification = Helper.InformationMessage(strNotification);
                Data["Notification"] = strNotification;

            } catch (Exception ex) {
                Data["Notification"] = Helper.ErrorMessage(ex.Message);
            } finally {
                GoToUrl("navigationgroup/settingnavigation/?groupid=" + groupid);
                base.RestService.Dispose();
            }
        }

        [HIS.Utils.Securities.Authorization(RoleAction = "sys-navigation")]
        public void SaveNavigationSetting() {
            StringReader stringReader = null;
            string strUri = string.Empty;
            int id = 0;
            int LastParent = 0;

            try {
                sysNavigation = new SysNavigation(); Utils.Helper.SetNullToEmptyString(sysNavigation);
                if (HttpContext.Current.Request["IsCreate"] != "true") {
                    try {
                        id = Convert.ToInt32(HttpContext.Current.Request["id"]);
                    } catch { }
                    strUri = Global.ServiceUriDictionary["nav"] + id + Global.ServiceUriDictionary["requestformat"];
                    ///Get Rest///
                    stringReader = base.RestService.GetJson(strUri);
                    sysNavigation = JsonConvert.DeserializeObject<SysNavigation>(stringReader.ReadToEnd());
                    LastParent = sysNavigation.ParentId;
                }

                sysNavigation.PostHandler<HISModels.Entities.SysNavigation>();
                sysNavigation.Slug = sysNavigation.DescValue.ToLower().ReplaceSpecialChar("-");
                int a = Convert.ToInt32(HttpContext.Current.Request["ParentId"].NullSafeToString());

                if (LastParent < Convert.ToInt32(HttpContext.Current.Request["ParentId"].NullSafeToString())) {
                    strUri = Global.ServiceUriDictionary["navparenthandle"] + id + Global.ServiceUriDictionary["requestformat"];
                    stringReader = base.RestService.PutJson(strUri, JsonConvert.SerializeObject(id));
                }

                strUri = Global.ServiceUriDictionary["nav"] + Global.ServiceUriDictionary["requestformat"];

                if (HttpContext.Current.Request["IsCreate"] == "true") {
                    stringReader = base.RestService.PostJson(strUri, JsonConvert.SerializeObject(sysNavigation));
                } else {
                    stringReader = base.RestService.PutJson(strUri, JsonConvert.SerializeObject(sysNavigation));
                }


                sysNavigation = JsonConvert.DeserializeObject<SysNavigation>(stringReader.ReadToEnd());

                if (sysNavigation != null) {
                    strNotification = Helper.SuccessMessage(base.RestService.ObjectResponse.Headers[HISModels.Enums.ResponseMessage.DetailHeadesMessageKey].ToString());
                } else {
                    strNotification = Helper.ErrorMessage(base.RestService.ObjectResponse.Headers[HISModels.Enums.ResponseMessage.DetailHeadesMessageKey].ToString());
                }


                strNotification = "{\"strNotification\": \"" + strNotification + "\"}";
                HttpContext.Current.Response.Write(strNotification);

            } catch (Exception ex) {
                strNotification = ex.Message;
            } finally {

                base.RestService.Dispose();
            }
        }

        private string GetParentNavigation(string Selected, int GroupID, int NotID) {
            string strCategory = string.Empty;
            string strUri = Global.ServiceUriDictionary["navsgroup"] + GroupID + Global.ServiceUriDictionary["requestformat"];

            StringReader strReader = base.RestService.GetJson(strUri);
            string s = strReader.ReadToEnd();
            List<SysNavigation> listNav = JsonConvert.DeserializeObject<List<SysNavigation>>(s);
            listNav = listNav.Where(a => a.Id != NotID).ToList();
            List<object[]> listGroup = new List<object[]>();
            listGroup.Add(new object[] { 0, "---Top---" });

            foreach (HISModels.Entities.SysNavigation item in listNav) listGroup.Add(new object[] { item.Id, item.DescValue });
            strCategory = Html.DropDown("ParentId", string.Empty, listGroup, Selected);
            return strCategory;
        }

        #endregion

        [HIS.Utils.Securities.Authorization(RoleAction = "sys-navigation")]
        public void SearchRole() {
            try {
                Data.Add("ddlocation", DropDownHospital(string.Empty));
                RenderFile("admins\\navigations\\seachrole.html");
            } catch (Exception ex) {
                HttpContext.Current.Response.Write(ex.Message);
            }
        }

        [HIS.Utils.Securities.Authorization(RoleAction = "sys-navigation")]
        public void SearchRoleTableList() {
            try {
                ///--------- Sample post to rest and get record as paging-------------/// 
                ///Create paging object///
                PostDataTablesNet pagingSearch = new PostDataTablesNet();
                pagingSearch.iDisplayLength = Convert.ToInt32(HttpContext.Current.Request["iDisplayLength"]);
                pagingSearch.iDisplayStart = Convert.ToInt32(HttpContext.Current.Request["iDisplayStart"]);

                string groupname = HttpContext.Current.Request["groupname"].NullSafeToString();
                string rolename = HttpContext.Current.Request["rolename"].NullSafeToString();
                int hospitalid = Convert.ToInt32(HttpContext.Current.Request["hospitalid"]);


                pagingSearch.sSearch = "rolename=" + rolename + ";hospitalid=" + hospitalid;

                pagingSearch.sEcho = Convert.ToInt32(HttpContext.Current.Request["sEcho"]);
                //
                ///Set Rest Url///
                string strUri = Global.ServiceUriDictionary["rolepaging"] + Global.ServiceUriDictionary["requestformat"];
                ///Post paging object to rest as json string///
                StringReader stringReader = base.RestService.PostJson(strUri, JsonConvert.SerializeObject(pagingSearch));
                ///Read response value///
                string strJson = stringReader.ReadToEnd();
                ///----------Consistenly clean up all object------------///
                stringReader.Dispose();
                base.RestService.Dispose();
                HttpContext.Current.Response.Write(strJson);
            } catch (Exception ex) {
                HttpContext.Current.Response.Write(ex.Message);
            }
        }

    }

}